package ch.zbw.sysventory.server.scanner;

public class IPHelper {

	public static int getTotalCountOfIPsInRange(String address1, String address2) {
		long firstIPValue = 0;
		long secondIPvalue = 0;
		short[] firstIP = stringToShort(address1);
		short[] secondIP = stringToShort(address2);

		for (byte i = 0; i < 4; i++) {
			firstIPValue += (long) (firstIP[i] * Math.pow(256, 3 - i));
			secondIPvalue += (long) (secondIP[i] * Math.pow(256, 3 - i));
		}

		return (int) (secondIPvalue - firstIPValue + 1);
	}

	public static String getNextIP(String ipAddress) {
		short[] ip = stringToShort(ipAddress);

		ip[3]++;

		for (byte i = 3; i > 0; i--) {
			if (ip[i] > 255) {
				ip[i] -= 256;
				ip[i - 1]++;
			}
		}

		if (ip[0] > 255) {
			ip[0] = 0;
		}

		String incIP = ip[0] + "." + ip[1] + "." + ip[2] + "." + ip[3];

		return incIP;
	}

	private static short[] stringToShort(String ipAddress) {
		String[] number = ipAddress.split("\\.");

		if (number.length != 4) {
			return null;
		}

		short[] ip = new short[4];

		for (byte i = 0; i < number.length; i++) {
			ip[i] = Short.parseShort(number[i]);
		}

		return ip;
	}
}
